package com.mdc.mansion.api.web.common.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.mdc.mansion.api.web.common.utils.login.LoginTicket;
import com.mdc.mansion.api.web.common.utils.login.LoginUtil;
import com.mdc.mansion.common.exception.BusinessException;
import com.mdc.mansion.common.response.Result;
import com.mdc.mansion.common.response.ResultCode;
import com.mdc.mansion.common.util.I18nUtil;
import com.mdc.mansion.common.util.JSONUtil;
import com.mdc.mansion.core.modules.restaurant.RestaurantService;
import com.mdc.mansion.core.modules.restaurant.RestaurantStaffService;
import com.mdc.mansion.dataaccess.common.context.ContextHolder;
import com.mdc.mansion.dataaccess.modules.restaurant.entity.Restaurant;
import com.mdc.mansion.dataaccess.modules.restaurant.entity.RestaurantStaff;

/**<p>com.mdc.mansion.api.web.common.interceptor.LoginInterceptor</p>
 * <p>Title: LoginInterceptor</p>
 * <p>Copyright: Copyright © 2010-2014</p>
 * <p>Company: jumei</p>
 * @author xiang.liu
 * @version 1.0
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private RestaurantStaffService restaurantStaffService;

    @Autowired
    private RestaurantService restaurantService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       if(handler.getClass().isAssignableFrom(HandlerMethod.class)){
           NoLoginCheck noLoginCheck = ((HandlerMethod) handler).getMethodAnnotation(NoLoginCheck.class);
           if(noLoginCheck != null){
              return true;
           }
        }
       String token = request.getParameter("token");
       String p = request.getParameter("p");
        if(StringUtils.equals(p,"h5")){
            try {
                registerContextData(token,p);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        // 从request中获取到json的参数串  解析出token
        LoginTicket loginTicket = LoginUtil.getLoginTicketByToken(token);
        if(loginTicket == null){
            processUnLogin(response);
            return false;
        }
        // 验证登录token是否过期
        boolean notTimeout = LoginUtil.loginTicketAvailable(loginTicket);
        if(!notTimeout){
            processUnLogin(response);
            return false;
        }else{// 没有过期 重设过期时间
            LoginUtil.putLoginTicketInCache(loginTicket);
        }
        try {
            registerContextData(loginTicket.getUsername(),p);
        } catch (Exception e) {
            e.printStackTrace();
            processUnLogin(response);
            return false;
        }
        return true;
    }

    private void processUnLogin(HttpServletResponse response)throws Exception{
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        StringBuffer responseSb = new StringBuffer();
        Result restultResult = new Result(ResultCode.COMMON_AUTH_ERROR);
        responseSb.append(JSONUtil.getInstance().writeValueAsString(restultResult));
        response.getWriter().println(responseSb.toString());
    }
    /**
     * 注册上下文信息
     * @date create_time：2017年12月31日 上午12:18:25
     * @param username
     */
    private void registerContextData(String username,String p){
        ContextHolder.registerP(p);
        ContextHolder.registerLoginAccount(username);
        // 获取商家信息   后期访问量大的时候可以采用缓存  一期不考虑
        RestaurantStaff restaurantStaff = restaurantStaffService.getByLoginAccount(username);
        if(restaurantStaff == null){
            throw new BusinessException(I18nUtil.getMessage("account.notexist", username));
        }
        String restaurantId = restaurantStaff.getRestaurantId();
        String roleType = restaurantStaff.getRoleType();
        ContextHolder.registerRestaurantId(restaurantId);
        ContextHolder.registerRoelType(roleType);
        // 继续注册其它信息
        ContextHolder.registerRestaurantStaff(restaurantStaff);
        if(StringUtils.isNotBlank(restaurantStaff.getRestaurantId())){
            Restaurant restaurant = restaurantService.get(restaurantStaff.getRestaurantId());
            if(restaurant==null){throw new BusinessException(restaurantStaff.getRestaurantId()+"的餐厅没找到");}
            ContextHolder.registerRestaurant(restaurant);
        }
    }
}
